package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserLoginService;
import com.usian.utils.common.AesUtil;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;

@Service
public class ApUserLoginServiceImpl extends BaseServiceImpl<ApUserMapper, ApUser> implements ApUserLoginService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    @SneakyThrows
    public ResponseResult login(LoginDto dto) {
//传入密码：579d9ec9d0c3d687aaa91289ac2854e4
        if (dto == null) return errorParam;
        if (StringUtils.isEmpty(dto.getPhone())) return ResponseResult.errorResult("请输入手机号");
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if (StringUtils.isEmpty(dto.getPassword())) return ResponseResult.errorResult("请输入密码");
        String md5 = AesUtil.decryptAES(dto.getPassword(), "NIfb&95GUY86Gfgh");
        boolean checkpw = BCrypt.checkpw(md5, apUser.getPassword());
        if (checkpw) {
            HashMap<String, Object> map = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }


/*    @SneakyThrows
    public static void main(String[] args) {
        //前端传输MD5加密后密码esc加密，先解密，

        String pswd = DigestUtils.md5DigestAsHex(("123456" + "123").getBytes());
        System.out.println("md5加密："+pswd);
        String s = AesUtil.encryptAES(pswd, "NIfb&95GUY86Gfgh");
        System.out.println("aes加密："+s);
        String s1 = AesUtil.decryptAES(s, "NIfb&95GUY86Gfgh");
        System.out.println("aes解密："+s1);
        String gensalt = BCrypt.gensalt();
        String pwd = BCrypt.hashpw(s1, gensalt);
        System.out.println("最终加密："+pwd);
        boolean checkpw = BCrypt.checkpw(s1,pwd);
        System.out.println("验证结果"+checkpw);
    }*/

}
